//
//  ZZContentDetailController.m
//  QQplayground
//
//  Created by zhangxy on 2018/6/20.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZContentDetailController.h"
#import "ZZDetailHeaderCell.h"
#import "ZZKeyboardView.h"
#import "ZZContentCommentController.h"
#import "ZZDetailCommentCell.h"
#define cellIdentifier @"ZZDetailCommentCell"
#import "ZZShareView.h"

@interface ZZContentDetailController ()<ZZTopicCellDelegate>

@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  UITableView *listTable;

@property(nonatomic,strong)  ZZDetailHeaderCell *headerCellView;
@property(nonatomic,strong)  ZZKeyboardView   *keyboardView;

@end

@implementation ZZContentDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = convertToString(_entity.user_info.user_name);
    [self setNavigationBar];
    
    
    self.navigationController.navigationBarHidden = NO;
    
    [self createTableView];
    
    
    
    _keyboardView = [[ZZKeyboardView alloc] initWithDelegate:self changeView:_listTable show:NO];
    _keyboardView.chatpterModel = _entity;
    __weak ZZContentDetailController *saveSelf = self;
    [_keyboardView setResultBlock:^(int code,NSString *text,id replayModel){
        if(code == 0){
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            [dict setObject:convertIntToString((int)saveSelf.entity.t_id) forKey:@"id"];
            [dict setObject:convertToString([UserUtil getUser].user_id) forKey:@"session_uid"];
            [dict setObject:convertToString(text) forKey:@"message"];
            if(replayModel!=nil){
                ZZTopicCommentEntity *tempModel = replayModel;
                [dict setObject:convertToString(tempModel.comment_id) forKey:@"quote_id"];
                [dict setObject:convertToString(tempModel.user_id) forKey:@"quote_uid"];
                
            }else{
                [dict setObject:@"0" forKey:@"quote_id"];
                [dict setObject:@"0" forKey:@"quote_uid"];
            }
            [NetworkUtil POST:API_publishComment(saveSelf.entity.nav_type) parameters:dict success:^(id responseObject, NSDictionary *dict) {
                ZZTopicCommentEntity *addModel = [[ZZTopicCommentEntity alloc] initWithDictionary:dict[@"data"]];
                [saveSelf.listArray insertObject:addModel atIndex:0];
                [saveSelf.listTable reloadData];
            } failure:^(NSError *error, NSString *message) {
                [PopUtil showMessage:dict[@"msg"]];
            }];
        }
    }];
}


- (UIView *)headerView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
    if(ZC_iPhoneX){
        _headerCellView = [[NSBundle mainBundle]loadNibNamed:@"ZZDetailHeaderCell" owner:nil options:nil].firstObject;
    }else{
        _headerCellView = [[NSBundle mainBundle]loadNibNamed:@"ZZDetailHeaderCell" owner:nil options:nil].firstObject;
    }
    _headerCellView.delegate = self;
    [_headerCellView dataToView:_entity];
    
    
    //    UIImage *backImage =[UIImage imageNamed:@"voice_bg"];
    //    headerView.layer.contents=(id)backImage.CGImage;
    //    self.view.layer.backgroundColor = [UIColor clearColor].CGColor;
    headerView.layer.backgroundColor = UIColor.clearColor.CGColor;
    [headerView addSubview:_headerCellView];
    
    return headerView;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [_keyboardView hideKeyboard];
}



-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier formY:0 withHeight:self.view.bounds.size.height-BottomHeight];
    
    [_listTable setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    _listTable.tableHeaderView = [self headerView];
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    
    [self setTableSeparatorInset];
    
    
    
    [self loadBegin];
}

-(void)lookMySelf:(UIButton *) btn{
    
}

-(void)loadBegin{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [_listArray removeAllObjects];
    [self loadMoreData];
}


-(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
    ZZHomeTopicEntity *topic = senderObj;
    
    if(type == ZZClickShare){
        ZZShareView *shareView = [[ZZShareView alloc] initWithShareType:ZZShareTypeTopic vc:self obj:topic];
        [shareView show];
    }
    if(type == ZZClickFav || type == ZZClickStar){
        NSString *typeName = @"fav";
        if(type == ZZClickStar){
            typeName = @"like";
        }
        [NetworkUtil POST:API_cancelvote(topic.nav_type)
               parameters:@{@"id":convertIntToString((int)topic.t_id),
                            @"type":typeName,
                            @"session_uid":[UserUtil getUser].user_id
                            }
                  success:^(id responseObject, NSDictionary *dict) {
                      [PopUtil showMessage:dict[@"msg"]];
                      if(type==ZZClickStar){
                          topic.fav_count = dict[@"data"][@"count"];
                      }else{
                          topic.like_count = dict[@"data"][@"count"];
                      }
                      //                      [_listTable reloadData];
                      [_headerCellView dataToView:topic];
                  } failure:^(NSError *error, NSString *message) {
                      
                  }];
    }
    if(type == ZZClickComment){
        ZZContentCommentController *vc = [[ZZContentCommentController alloc] init];
        vc.entity = topic;
        [self openPushVC:vc];
    }
    if(type == ZZClickOpenVC){
        [self openPushVC:senderObj];
    }
}


/**
 加载更多
 */
-(void)loadMoreData{
    [NetworkUtil POST:API_HOST parameters:@{} success:^(id responseObject, NSDictionary *dict) {
        NSArray *arr = dict[@"data"];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [PopUtil showMessage:message];
    }];
}



#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 54;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 54)];
    [headerView setBackgroundColor:UIColor.whiteColor];
    
    UIImageView *lineView = [self createImageView];
    [lineView setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    [lineView setFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    [headerView addSubview:lineView];
    
    UILabel *labTip = [self createLabel];
    [labTip setFont:FontThirteen];
    [labTip setTextColor:UIColorFromRGB(Text6Color)];
    [labTip setFrame:CGRectMake(10, 10, ScreenWidth - 64, 44)];
    [headerView addSubview:labTip];
    if(section == 0){
        [_headerCellView dataToView:_entity];
        _listTable.tableHeaderView = _headerCellView;
        
        [labTip setText:@"热门评论"];
    }else{
        [labTip setText:@"全部评论"];
        
        UIButton *btnOnlySelf = [self createButton];
        [btnOnlySelf setTitle:@"只看楼主" forState:0];
        [btnOnlySelf setFrame:CGRectMake(ScreenWidth-73, (44-18)/2+10, 63, 18)];
        [btnOnlySelf setTitleColor:UIColorFromRGB(TextWhiteColor) forState:0];
        [btnOnlySelf.titleLabel setFont:FontThirteen];
        btnOnlySelf.layer.cornerRadius = 3.0f;
        btnOnlySelf.layer.masksToBounds = YES;
        [btnOnlySelf setBackgroundColor:UIColorFromRGB(TextLinkColor)];
        [btnOnlySelf addTarget:self action:@selector(lookMySelf:) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:btnOnlySelf];
    }
    
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 1){
        return _listArray.count;
    }else{
        return _entity.thread_list.count;
    }
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZDetailCommentCell *cell = (ZZDetailCommentCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZDetailCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    if(indexPath.section == 0){
        [cell dataToView: _entity.thread_list[indexPath.row]];
    }else{
        [cell dataToView:_listArray[indexPath.row]];
    }
    
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    VipModel *model=[_listArray objectAtIndex:indexPath.row];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.row+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
